<?php
if (!defined('ABSPATH')) { exit; }

// 获取安全模块实例
$security = wp_spider_premium_security();
$is_premium = $security->is_premium_activated();

// 获取主插件实例用于许可证验证
global $wp_spider_monitor;

// 处理授权设置
if (isset($_POST['action'])) {
    check_admin_referer('wp_spider_license_nonce');
    
    $action = sanitize_text_field($_POST['action']);
    $license_key = sanitize_text_field($_POST['license_key'] ?? '');
    $expires_at = null;
    
    if (!empty($_POST['expires_at'])) {
        $expires_at = strtotime(sanitize_text_field($_POST['expires_at']));
    }
    
    switch ($action) {
        case 'activate_license':
            // 激活授权
            if (!empty($license_key)) {
                // 使用订阅客户端进行激活
                $subscription_client = new Spider_Subscription_Client();
                $activation_result = $subscription_client->activate_license($license_key);
                
                if ($activation_result['success']) {
                    $security->set_premium_status(true, $expires_at);
                    echo '<div class="notice notice-success"><p>✅ PRO版本已成功激活！所有高级功能现已可用。</p></div>';
                } else {
                    echo '<div class="notice notice-error"><p>❌ 激活失败：' . esc_html($activation_result['message']) . '</p></div>';
                }
            } else {
                // 没有许可证密钥，拒绝激活
                echo '<div class="notice notice-error"><p>❌ 必须提供有效的许可证密钥才能激活PRO版本！</p></div>';
            }
            break;
            
        case 'deactivate_license':
            // 取消授权 - 先调用订阅客户端停用，再同步到安全模块
            $subscription_client = new Spider_Subscription_Client();
            $deactivation_result = $subscription_client->deactivate_license();
            
            if ($deactivation_result['success']) {
                $security->set_premium_status(false, null);
                echo '<div class="notice notice-info"><p>ℹ️ PRO版本已停用。所有高级功能已被禁用。</p></div>';
            } else {
                // 如果远程停用失败，仍然在本地停用
                $security->set_premium_status(false, null);
                echo '<div class="notice notice-warning"><p>⚠️ 本地PRO版本已停用，但远程停用失败：' . esc_html($deactivation_result['message']) . '</p></div>';
            }
            break;
            
        case 'update_license':
            // 更新设置
            $is_active = isset($_POST['is_active']) && $_POST['is_active'] === '1';
            
            if (!empty($license_key)) {
                if ($is_active) {
                    // 如果要激活，先进行激活操作
                    $subscription_client = new Spider_Subscription_Client();
                    $activation_result = $subscription_client->activate_license($license_key);
                    
                    if ($activation_result['success']) {
                        $security->set_premium_status(true, $expires_at);
                        echo '<div class="notice notice-success"><p>✅ 许可证激活成功！PRO版本已启用。</p></div>';
                    } else {
                        echo '<div class="notice notice-error"><p>❌ 激活失败：' . esc_html($activation_result['message']) . '</p></div>';
                    }
                } else {
                    // 如果要停用，进行停用操作
                    $subscription_client = new Spider_Subscription_Client();
                    $deactivation_result = $subscription_client->deactivate_license();
                    
                    if ($deactivation_result['success']) {
                        $security->set_premium_status(false, null);
                        echo '<div class="notice notice-info"><p>ℹ️ 许可证已停用！PRO版本已禁用。</p></div>';
                    } else {
                        echo '<div class="notice notice-error"><p>❌ 停用失败：' . esc_html($deactivation_result['message']) . '</p></div>';
                    }
                }
            } else {
                // 没有许可证密钥，拒绝更新
                echo '<div class="notice notice-error"><p>❌ 必须提供有效的许可证密钥才能更新授权状态！</p></div>';
            }
            break;
    }
    
    // 刷新状态 - 强制重新检查所有模块状态
    $is_premium = $security->is_premium_activated();
    
    // 如果是停用操作，强制清除所有缓存并重新同步
    if ($action === 'deactivate_license') {
        // 清除订阅客户端缓存
        if (isset($GLOBALS['spider_subscription_client'])) {
            $client = $GLOBALS['spider_subscription_client'];
            $client->clear_cache();
        }
        
        // 强制重新检查状态
        $is_premium = $security->is_premium_activated();
    }
}

// 安全地获取当前授权信息（优先读取本地激活缓存，保证激活后立即展示）
$status_info = get_option('spider_license_activation');
if (!$status_info || empty($status_info['is_active'])) {
    $status_info = $security->get_license_info();
}

// 调试信息：检查激活状态一致性
$debug_info = array();
if (isset($GLOBALS['spider_subscription_client'])) {
    $client = $GLOBALS['spider_subscription_client'];
    $debug_info['subscription_client'] = $client->is_activated();
    $debug_info['license_key'] = get_option('spider_license_key', '');
}
$debug_info['security_module'] = $security->is_premium_activated();
$debug_info['encrypted_status'] = get_option('wp_spider_premium_status_encrypted') ? 'exists' : 'not_exists';
?>

<div class="wrap">
    <h1>🔐 许可证管理</h1>
    <p class="description">管理WordPress Spider Monitor的授权状态和许可证设置</p>
    
    <div class="license-management">
        <div class="license-status-card">
            <h2>当前授权状态</h2>
            <div class="status-indicator <?php echo $is_premium ? 'active' : 'inactive'; ?>">
                <div class="status-dot"></div>
                <span class="status-text">
                    <?php echo $is_premium ? '已激活PRO版本' : '未激活PRO版本'; ?>
                </span>
            </div>
            
            <?php if ($is_premium && !empty($status_info)): ?>
            <div class="license-details">
                <p><strong>激活时间:</strong> <?php 
                    $activated_at = $status_info['activated_at'] ?? 0;
                    if (is_numeric($activated_at)) {
                        echo date('Y-m-d H:i:s', $activated_at);
                    } else {
                        echo esc_html($activated_at);
                    }
                ?></p>
                <?php if (isset($status_info['expires_at']) && $status_info['expires_at']): ?>
                <p><strong>过期时间:</strong> <?php 
                    $expires_at = $status_info['expires_at'];
                    if (is_numeric($expires_at)) {
                        echo date('Y-m-d H:i:s', $expires_at);
                    } else {
                        echo esc_html($expires_at);
                    }
                ?></p>
                <?php endif; ?>
                <p><strong>授权域名:</strong> <?php echo $status_info['domain'] ?? '未知'; ?></p>
            </div>
            <?php endif; ?>
        </div>
        
        <div class="license-settings-card">
            <h2>授权设置</h2>
            
            <?php if ($is_premium): ?>
                <!-- 已激活状态 -->
                <div class="activation-status active">
                    <div class="status-indicator">
                        <span class="status-icon">✅</span>
                        <span class="status-text">PRO版本已激活</span>
                    </div>
                    <p class="status-description">所有高级功能现已可用，包括7天和30天数据统计等。</p>
                </div>
                
                <div class="action-buttons">
                    <form method="post" action="" style="display: inline-block;">
                        <?php wp_nonce_field('wp_spider_license_nonce'); ?>
                        <input type="hidden" name="action" value="deactivate_license">
                        <input type="submit" class="button button-secondary deactivate-btn" value="停用PRO版本" 
                               onclick="return confirm('确定要停用PRO版本吗？停用后所有高级功能将被禁用。');">
                    </form>
                </div>
            <?php else: ?>
                <!-- 未激活状态 -->
                <div class="activation-status inactive">
                    <div class="status-indicator">
                        <span class="status-icon">❌</span>
                        <span class="status-text">PRO版本未激活</span>
                    </div>
                    <p class="status-description">激活PRO版本以解锁所有高级功能，包括7天和30天数据统计等。</p>
                </div>
                
                <form method="post" action="" class="activation-form">
                    <?php wp_nonce_field('wp_spider_license_nonce'); ?>
                    <input type="hidden" name="action" value="activate_license">
                    
                    <table class="form-table">
                        <tr>
                            <th scope="row">许可证密钥</th>
                            <td>
                                <input type="text" name="license_key" class="regular-text" placeholder="输入许可证密钥（可选）" 
                                       value="<?php echo esc_attr($status_info['license_key'] ?? ''); ?>">
                                <p class="description">输入有效的许可证密钥以验证授权（可选，留空可临时激活）</p>
                            </td>
                        </tr>
                        
                        <tr>
                            <th scope="row">过期时间</th>
                            <td>
                                <input type="datetime-local" name="expires_at" class="regular-text" 
                                       value="<?php 
                                       if ($status_info['expires_at']) {
                                           $expires_at = $status_info['expires_at'];
                                           if (is_numeric($expires_at)) {
                                               echo date('Y-m-d\TH:i', $expires_at);
                                           } else {
                                               echo esc_attr($expires_at);
                                           }
                                       }
                                       ?>">
                                <p class="description">设置授权过期时间（可选，留空表示永久有效）</p>
                            </td>
                        </tr>
                    </table>
                    
                    <p class="submit">
                        <input type="submit" class="button button-primary activate-btn" value="激活PRO版本">
                    </p>
                </form>
            <?php endif; ?>
            
            <!-- 高级设置（始终显示） -->
            <div class="advanced-settings">
                <h3>高级设置</h3>
                <form method="post" action="">
                    <?php wp_nonce_field('wp_spider_license_nonce'); ?>
                    <input type="hidden" name="action" value="update_license">
                    
                    <table class="form-table">
                        <tr>
                            <th scope="row">授权状态</th>
                            <td>
                                <label>
                                    <input type="checkbox" name="is_active" value="1" <?php checked($is_premium); ?>>
                                    激活PRO版本
                                </label>
                                <p class="description">勾选此项将激活PRO版本的所有功能</p>
                            </td>
                        </tr>
                        
                        <tr>
                            <th scope="row">许可证密钥</th>
                            <td>
                                <input type="text" name="license_key" class="regular-text" placeholder="输入许可证密钥（可选）" 
                                       value="<?php echo esc_attr($status_info['license_key'] ?? ''); ?>">
                                <p class="description">输入有效的许可证密钥以验证授权</p>
                            </td>
                        </tr>
                        
                        <tr>
                            <th scope="row">过期时间</th>
                            <td>
                                <input type="datetime-local" name="expires_at" class="regular-text" 
                                       value="<?php 
                                       if ($status_info['expires_at']) {
                                           $expires_at = $status_info['expires_at'];
                                           if (is_numeric($expires_at)) {
                                               echo date('Y-m-d\TH:i', $expires_at);
                                           } else {
                                               echo esc_attr($expires_at);
                                           }
                                       }
                                       ?>">
                                <p class="description">设置授权过期时间（可选，留空表示永久有效）</p>
                            </td>
                        </tr>
                    </table>
                    
                    <p class="submit">
                        <input type="submit" class="button button-secondary" value="保存设置">
                    </p>
                </form>
            </div>
        </div>
        
        <div class="debug-info-card">
            <h2>调试信息</h2>
            <div class="debug-details">
                <p><strong>订阅客户端状态:</strong> <?php echo $debug_info['subscription_client'] ? '✅ 已激活' : '❌ 未激活'; ?></p>
                <p><strong>安全模块状态:</strong> <?php echo $debug_info['security_module'] ? '✅ 已激活' : '❌ 未激活'; ?></p>
                <p><strong>许可证密钥:</strong> <?php echo !empty($debug_info['license_key']) ? '✅ 已设置' : '❌ 未设置'; ?></p>
                <p><strong>加密状态:</strong> <?php echo $debug_info['encrypted_status'] === 'exists' ? '✅ 存在' : '❌ 不存在'; ?></p>
                <?php if ($debug_info['subscription_client'] !== $debug_info['security_module']): ?>
                <p style="color: red;"><strong>⚠️ 状态不一致！</strong> 正在同步...</p>
                <?php endif; ?>
            </div>
        </div>
        
        <div class="security-info-card">
            <h2>安全信息</h2>
            <div class="security-features">
                <div class="feature-item">
                    <span class="feature-icon">🔒</span>
                    <div class="feature-content">
                        <h3>服务器端验证</h3>
                        <p>所有付费功能验证都在服务器端进行，防止客户端绕过</p>
                    </div>
                </div>
                
                <div class="feature-item">
                    <span class="feature-icon">🔐</span>
                    <div class="feature-content">
                        <h3>加密存储</h3>
                        <p>授权状态使用AES-256加密存储，确保数据安全</p>
                    </div>
                </div>
                
                <div class="feature-item">
                    <span class="feature-icon">🛡️</span>
                    <div class="feature-content">
                        <h3>令牌验证</h3>
                        <p>使用时间戳和指纹验证，防止重放攻击</p>
                    </div>
                </div>
                
                <div class="feature-item">
                    <span class="feature-icon">🌐</span>
                    <div class="feature-content">
                        <h3>域名绑定</h3>
                        <p>授权与域名绑定，防止跨域使用</p>
                    </div>
                </div>
            </div>
        </div>
        
        <div class="premium-features-card">
            <h2>PRO版本功能</h2>
            <div class="features-grid">
                <div class="feature-card">
                    <h3>📊 7天数据查看</h3>
                    <p>查看最近7天的详细蜘蛛访问数据</p>
                </div>
                
                <div class="feature-card">
                    <h3>📈 30天数据查看</h3>
                    <p>查看最近30天的详细蜘蛛访问数据</p>
                </div>
                
                <div class="feature-card">
                    <h3>🔍 高级分析</h3>
                    <p>访问路径分析、文章爬取分析等高级功能</p>
                </div>
                
                <div class="feature-card">
                    <h3>📋 详细统计</h3>
                    <p>Top蜘蛛统计、IP段分析等详细统计功能</p>
                </div>
            </div>
        </div>
    </div>
</div>

<style>
.license-management {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 20px;
    margin-top: 20px;
}

.license-status-card,
.license-settings-card,
.security-info-card,
.premium-features-card,
.debug-info-card {
    background: white;
    border: 1px solid #ccd0d4;
    border-radius: 8px;
    padding: 20px;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.debug-info-card {
    background: #f8f9fa;
    border-color: #007cba;
}

.debug-details p {
    margin: 8px 0;
    font-size: 14px;
}

.premium-features-card {
    grid-column: 1 / -1;
}

.status-indicator {
    display: flex;
    align-items: center;
    gap: 10px;
    margin: 15px 0;
    padding: 10px;
    border-radius: 6px;
    background: #f8f9fa;
}

.status-indicator.active {
    background: #d4edda;
    color: #155724;
}

.status-indicator.inactive {
    background: #f8d7da;
    color: #721c24;
}

.status-dot {
    width: 12px;
    height: 12px;
    border-radius: 50%;
    background: #6c757d;
}

.status-indicator.active .status-dot {
    background: #28a745;
}

.status-indicator.inactive .status-dot {
    background: #dc3545;
}

.license-details {
    margin-top: 15px;
    padding: 15px;
    background: #f8f9fa;
    border-radius: 6px;
}

.license-details p {
    margin: 5px 0;
    font-size: 14px;
}

.security-features {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 15px;
    margin-top: 15px;
}

.feature-item {
    display: flex;
    align-items: flex-start;
    gap: 10px;
    padding: 15px;
    background: #f8f9fa;
    border-radius: 6px;
}

.feature-icon {
    font-size: 24px;
    flex-shrink: 0;
}

.feature-content h3 {
    margin: 0 0 5px 0;
    font-size: 16px;
}

.feature-content p {
    margin: 0;
    font-size: 14px;
    color: #666;
}

.features-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
    gap: 15px;
    margin-top: 15px;
}

.feature-card {
    padding: 15px;
    background: #f8f9fa;
    border-radius: 6px;
    border-left: 4px solid #007cba;
}

.feature-card h3 {
    margin: 0 0 10px 0;
    font-size: 16px;
}

.feature-card p {
    margin: 0;
    font-size: 14px;
    color: #666;
}

/* 激活状态样式 */
.activation-status {
    padding: 20px;
    border-radius: 8px;
    margin-bottom: 20px;
    border: 2px solid;
}

.activation-status.active {
    background: #f0f8f0;
    border-color: #28a745;
}

.activation-status.inactive {
    background: #fff5f5;
    border-color: #dc3545;
}

.status-indicator {
    display: flex;
    align-items: center;
    gap: 10px;
    margin-bottom: 10px;
}

.status-icon {
    font-size: 20px;
}

.status-text {
    font-size: 18px;
    font-weight: 600;
}

.activation-status.active .status-text {
    color: #28a745;
}

.activation-status.inactive .status-text {
    color: #dc3545;
}

.status-description {
    margin: 0;
    color: #666;
    font-size: 14px;
}

/* 操作按钮样式 */
.action-buttons {
    margin-top: 20px;
}

.activate-btn {
    background: linear-gradient(135deg, #28a745, #20c997) !important;
    border: none !important;
    color: white !important;
    padding: 12px 24px !important;
    font-size: 16px !important;
    font-weight: 600 !important;
    border-radius: 6px !important;
    box-shadow: 0 2px 8px rgba(40, 167, 69, 0.3) !important;
    transition: all 0.3s ease !important;
}

.activate-btn:hover {
    background: linear-gradient(135deg, #20c997, #17a2b8) !important;
    transform: translateY(-2px) !important;
    box-shadow: 0 4px 12px rgba(40, 167, 69, 0.4) !important;
}

.deactivate-btn {
    background: linear-gradient(135deg, #dc3545, #c82333) !important;
    border: none !important;
    color: white !important;
    padding: 10px 20px !important;
    font-size: 14px !important;
    font-weight: 600 !important;
    border-radius: 6px !important;
    box-shadow: 0 2px 8px rgba(220, 53, 69, 0.3) !important;
    transition: all 0.3s ease !important;
}

.deactivate-btn:hover {
    background: linear-gradient(135deg, #c82333, #bd2130) !important;
    transform: translateY(-2px) !important;
    box-shadow: 0 4px 12px rgba(220, 53, 69, 0.4) !important;
}

/* 高级设置样式 */
.advanced-settings {
    margin-top: 30px;
    padding-top: 20px;
    border-top: 1px solid #e0e0e0;
}

.advanced-settings h3 {
    color: #333;
    margin-bottom: 15px;
    font-size: 16px;
}

/* 激活表单样式 */
.activation-form {
    background: #f8f9fa;
    padding: 20px;
    border-radius: 8px;
    border: 1px solid #e0e0e0;
}

@media (max-width: 768px) {
    .license-management {
        grid-template-columns: 1fr;
    }
    
    .security-features {
        grid-template-columns: 1fr;
    }
}
</style>